#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
from EU.models import Broadcast
# from datetime import datetime
from django.utils import timezone
import logging

__author__ = "Yunpeng Li <ypli.chn@outlook.com.com>"


class BroadcastBox(object):
    """
    广播箱（单例）
    用来存放广播列表
    """
    def __init__(self):
        pass


    def __new__(cls, *args, **kwargs):
        """
        单例
        :param args:
        :param kwargs:
        :return:
        """
        if not hasattr(cls,'_instance'):
            cls._instance = super(BroadcastBox,cls).__new__(cls,*args,**kwargs)
            cls._instance._update_broadcast_list()
            cls._read_dict = {}
        return cls._instance

    def _add_broadcast(self,broadcast):
        """
        添加一条广播
        :param broadcast: 广播
        :return: None
        """
        if not isinstance(broadcast,Broadcast):
            raise AttributeError('[_add_broadcast]Attribute must be Broadcast')
        print("管理员%s 添加一条广播:%s"%(broadcast.admin_id,broadcast.message))
        broadcast.save()
        self.broadcast_list.append(broadcast)


    def _update_broadcast_list(self):
        """
        更新广播列表（从数据库获取）
        :return:  广播数组
        """
        self.broadcast_list  = []
        for broadcast in Broadcast.objects.filter(deadline__gte = timezone.now()):
            self.broadcast_list.append(broadcast)
        logging.info("从数据库获取到%d条广播" % len(self.broadcast_list))
        print("从数据库获取到%d条广播" % len(self.broadcast_list))


    def delete_broadcast(self,broadcast_id):
        """
        删除一条广播
        :return:
        """
        print("已删除 %d" % broadcast_id)
        try:
            broadcast = Broadcast.objects.get(id=broadcast_id)
            broadcast.delete()
        except Exception as e:
            pass

        for broadcast_in_list in self.broadcast_list:
            if broadcast_in_list.id == broadcast_id:
                self.broadcast_list.remove(broadcast_in_list)


    def get_broadcast(self,device_id):
        """
        获取未读广播
        :param device_id: 设备id
        :return: 广播数组
        """
        # self._update_broadcast_list()
        print("broadcast_list个数 %d" % len(self.broadcast_list))
        print("device_id = %s" % device_id)
        readed_set = set()
        if device_id in self._read_dict:
            print("已经初始化过set了")
            readed_set = self._read_dict[device_id]
            print("readed_set---> %s" % readed_set)
        else:
            print("第一次访问,初始化set")
            self._read_dict[device_id] = readed_set
            print(self._read_dict[device_id])

        result_list = []
        for broadcast in self.broadcast_list:
            if(broadcast.deadline - timezone.now() < timezone.timedelta(0)):
                # 剔除过期广播
                self.broadcast_list.remove(broadcast)
                logging.info("[%s] 已过期,剔除" % broadcast.message)
                continue

            if broadcast.id in readed_set:
                continue
            else:
                result_list.append(broadcast.message)
                readed_set.add(broadcast.id)
                print("readed_set添加%d" % broadcast.id)

        logging.info("返回未读广播%d条",len(result_list))
        return result_list

    def post_broadcast(self,admin_id,message,time_length):
        """
        发布一条广播
        :param admin_id: 管理员id
        :param message: 广播内容
        :param time_length: 广播时长
        :return:
        """
        broadcast = Broadcast()
        broadcast.date = timezone.now()
        broadcast.message = message
        broadcast.deadline = broadcast.date + timezone.timedelta(seconds=time_length)
        broadcast.admin_id = admin_id
        self._add_broadcast(broadcast)
        return broadcast
